package com.wct.springcloud.controller;

import com.wct.springcloud.model.Dept;
import com.wct.springcloud.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date: 2019/12/11 15:31
 */
@Slf4j
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient client;

    @PostMapping(value = "/dept/add")
    public boolean add(@RequestBody Dept dept) {
        log.info("/dept/add/ dept: {}", dept.toString());
        return deptService.add(dept);
    }

    @GetMapping(value = "/dept/get/{id}")
    public Dept get(@PathVariable("id") Integer id) {
        log.info("/dept/get/ id: {}", id.toString());
        return deptService.get(id);
    }

    @GetMapping(value = "/dept/list")
    public List<Dept> list() {
        log.info("/dept/list list: ");
        return deptService.list();
    }

    @GetMapping(value = "/dept/discovery")
    public Object discovery() {
        // 从eureka获取服务
        List<String> services = client.getServices();
        for (String s : services) {
            log.info("service: {}", s);
        }

        // 根据Application name获取微服务访问信息
        List<ServiceInstance> serviceInstances = client.getInstances("microservicecloud-dept-provider");
        for (ServiceInstance element : serviceInstances) {
            log.info("serviceId: {} \t host: {} \t url: {} \t port: {} \t instanceId: {}",
                    element.getServiceId(), element.getHost(), element.getUri(), element.getPort(), element.getInstanceId());
        }

        return this.client;
    }
}
